package address

import (
	"gorm.io/gorm"
	"shop/database/mysql"
	"shop/formdata"
)

type Address struct {
	gorm.Model
	UserID      int    `gorm:"type:int(11);" json:"userID"`
	Recipient   string `json:"recipient" gorm:"type:varchar(20);"`
	Phone       string `json:"phone" gorm:"type:char(11);"`
	Province    string `json:"province" gorm:"type:varchar(20);"`
	City        string `json:"city" gorm:"type:varchar(20);"`
	Village     string `json:"village" gorm:"type:varchar(20);"`
	AddressLine string `json:"addressLine" gorm:"type:varchar(255);"`
	Table       string `json:"table" gorm:"type:varchar(20);"`
	UnDefault   int    `json:"un_default" gorm:"type:tinyint(1);comment:1默认，0非默认"`
}

func (a *Address) AddressAdd(add formdata.Address) (address *Address, err error) {
	return address, mysql.WithMysql(func(db *gorm.DB) error {
		address = &Address{
			Recipient:   add.Recipient,
			Phone:       add.Phone,
			Province:    add.Province,
			City:        add.City,
			Village:     add.Village,
			AddressLine: add.AddressLine,
			Table:       add.Table,
			UnDefault:   add.UnDefault,
		}
		return db.Table("addresses").Create(&address).Error
	})
}

func (a *Address) AddressList() (address []Address, err error) {
	return address, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("addresses").Find(&address).Error
	})
}

func (a *Address) AddressInfoByID(addID int) (address *Address, err error) {
	return address, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("addresses").Where("id = ?", addID).First(&address).Error
	})
}
